package util

import (
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"strings"
)

func RequestParser(req *http.Request) []byte {
	result := make([]byte, 1024*20)
	str := ""
	str += req.Method
	str += " " + req.URL.String()
	str += " " + req.Proto
	str += "\r\n"
	req.Header.Set("host", "127.0.0.1")
	for k, v := range map[string][]string(req.Header) {
		value := strings.Join(v, ",")
		str += k + ": " + value + "\r\n"
	}
	str += "\r\n"

	bd, _ := ioutil.ReadAll(req.Body)

	result = []byte(str)
	result = append(result, bd...)

	return result
}

func HttpNotFound(w io.Writer) {
	response := fmt.Sprintf("HTTP/1.0 404 Not Found\r\nContent-Length:%d\r\n\r\n%s", 0, "")

	w.Write([]byte(response))
}

func HttpError(w io.Writer, err error) {
	l := len(err.Error())
	response := fmt.Sprintf("HTTP/1.0 200 OK\r\nContent-Length:%d\r\n\r\n%s", l, err.Error())

	w.Write([]byte(response))
}

func HttpOk(w io.Writer, data string) {
	l := len(data)
	response := fmt.Sprintf("HTTP/1.0 200 OK\r\nContent-Length:%d\r\n\r\n%s", l, data)

	w.Write([]byte(response))
}
